<template>
  <div>
    <el-dialog :title="titleText" :visible.sync="showDialog" top="0" width="90%" :close-on-click-modal="false" @close="cancel()">
      <div class="top-form">
        <el-form ref="form" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="产线名称：" prop="productLineName" class="w50p">
            <el-input v-model="formData.productLineName" placeholder="请输入产线名称" clearable />
          </el-form-item>
          <el-form-item label="关联加工产品：" prop="lineProductMapperList" class="w50p">
            <el-select v-model="formData.lineProductMapperList" multiple placeholder="请选择关联加工产品" clearable filterable>
              <el-option v-for="item in productList" :key="item.productId" :label="item.productName" :value="item.productId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="top-header">
        <div class="left">
          <el-button type="primary" @click="showDialogInner = true">添加</el-button>
          <el-button :disabled="!delActive" type="danger" @click="del()">删除</el-button>
        </div>
        <div class="right">
          <span>关联设备列表</span>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" stripe border height="300px" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="$utils.selectable" width="55" />
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="equipmentName" label="设备名称" />
          <el-table-column prop="equModelName" label="所属设备型号">
            <template v-if="!('index' in scope.row)" slot-scope="scope">
              {{ scope.row.equModelName || scope.row.equipmentTypeName }}
            </template>
          </el-table-column>
          <el-table-column prop="produceDate" label="生产日期" />
          <el-table-column prop="statusText" label="状态">
            <template v-if="!('index' in scope.row)" slot-scope="scope">
              <el-switch :value="scope.row.status === 'ENABLE'" disabled />
            </template>
          </el-table-column>
        </el-table>
        <Pagination :light="true" :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button :loading="saveLoading" type="primary" class="savebtn" @click="save()">确 定</el-button>
      </div>
    </el-dialog>
    <ChooseEquDialog v-model="showDialogInner" title-text="添加设备" :type="3" @sub="importSub" />
  </div>
</template>

<script>
import api from '@/api/processing-management/basic-info-manage/product-line';
import Pagination from '@/components/Pagination';
import ChooseEquDialog from '../../equip-manage/equip-standing-book/components/choose-dialog.vue';
export default {
  name: 'WorkmanshipDialog',
  components: { Pagination, ChooseEquDialog },
  props: {
    value: Boolean,
    selectedItem: {
      type: Object,
      default: null
    },
    productList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      formData: {
        productLineName: '',
        lineProductMapperList: []
      },
      saveLoading: false,
      showDialog: false,
      showDialogInner: false,
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      tableData: [],
      tableDataAll: [],
      delActive: false,
      selectedList: [],
      rules: {
        productLineName: [
          {
            required: true,
            message: '请输入产线名称'
          }
        ],
        lineProductMapperList: [
          {
            required: true,
            message: '请选择关联加工产品'
          }
        ]
      }
    };
  },
  computed: {
    titleText() {
      return this.selectedItem ? '编辑产线' : '新增产线';
    }
  },
  watch: {
    value(v) {
      this.showDialog = v;
      if (!v) {
        setTimeout(() => {
          this.reset();
        }, 250);
      } else {
        this.init();
      }
    }
  },
  created() {
    this.showDialog = this.value;
  },
  mounted() {},
  methods: {
    init() {
      const { selectedItem } = this;
      if (selectedItem) {
        this.formData = {
          productLineName: selectedItem.productLineName,
          lineProductMapperList: selectedItem.lineProductMapperList.map(i => i.productId)
        };
        this.tableDataAll = selectedItem.lineEquMapperList;
        this.getList();
      } else {
        this.tableDataAll = [];
        this.getList();
      }
    },
    reset() {
      this.formData = {
        productLineName: '',
        lineProductMapperList: []
      };
      this.$refs.form.resetFields();
      this.tableDataAll = [];
      this.getList();
      this.saveLoading = false;
      this.selectedList = [];
    },
    save() {
      const { formData, selectedItem, tableDataAll, productList } = this;
      this.$refs['form'].validate(async valid => {
        if (valid) {
          const lineEquMapperList = tableDataAll;
          const lineProductMapperList = productList.filter(i => {
            return formData.lineProductMapperList.includes(i.productId);
          });
          const paylod = {
            ...formData,
            lineEquMapperList,
            lineProductMapperList
          };
          this.saveLoading = true;
          if (selectedItem) {
            api
              .editProductionLine({ productLineId: selectedItem.productLineId, ...paylod })
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          } else {
            api
              .addProductionLine(paylod)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.close();
                  this.$emit('reflash');
                }
              })
              .finally(_ => {
                this.saveLoading = false;
              });
          }
        }
      });
    },
    close() {
      this.$emit('input', false);
    },
    cancel() {
      this.$emit('input', false);
    },
    cancelInner() {
      this.showDialogInner = false;
    },
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.equipmentCode;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getList();
    },
    del() {
      this.handleDelete(this.selectedList);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          const { tableDataAll } = this;
          // 首先，将待删除的列表转换为一个Set，以提高查找效率
          const toDeleteSet = new Set(list);
          // 使用filter方法删除totalList中的待删除项
          this.tableDataAll = tableDataAll.filter(item => {
            // 检查当前项的id是否不在待删除的Set中
            return !toDeleteSet.has(item.equipmentCode);
          });
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(_ => {});
    },
    getList() {
      const { tableDataAll, currentPage, pageSize } = this;
      this.totalSize = tableDataAll.length;
      // 计算当前页应该显示的数据的起始索引
      const startIndex = (currentPage - 1) * pageSize;

      // 计算当前页应该显示的数据的结束索引
      const endIndex = startIndex + pageSize;

      // 使用 slice 方法获取当前页的数据
      const currentPageData = tableDataAll.slice(startIndex, endIndex);
      this.tableData = this.$utils.addblankmet(currentPageData, pageSize);
    },
    importSub(items) {
      const { tableDataAll } = this;
      const existingIds = new Set(tableDataAll.map(item => item.equipmentCode));
      this.tableDataAll = [...this.tableDataAll, ...items.filter(item => !existingIds.has(item.equipmentCode))];
      this.getList();
      this.showDialogInner = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.top-header {
  width: 100%;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  .left {
    flex: 1;
  }
}
.table-wrapper {
  position: relative;
  padding-bottom: 50px;
  box-sizing: border-box;
}
.notice {
  line-height: normal;
  margin-top: 10px;
  font-size: 12px;
  color: #333;
}
</style>
